package home

import (
	"fmt"
	"adai.design/homeserver/members"
	"encoding/json"
	"adai.design/homeserver/log"
)

// 场景
type Scene struct {
	Id 		string		`json:"id" bson:"id"`
	Name 	string		`json:"name" bson:"name"`
	Icon 	string 		`json:"icon" bson:"icon"`
	Type 	string		`json:"type" bson:"type"`
	Actions []*Action	`json:"actions" bson:"actions"`
}

func (s *Scene) execute(h *Home) error {
	return h.containerManager.executeActions(h, s.Actions...)
}

type SceneManager struct {
	scenes 	[]*Scene
}

func (sm *SceneManager) SceneManager(h *Home, id string) error {
	for _, s := range sm.scenes {
		if s.Id == id {
			return h.containerManager.executeActions(h, s.Actions...)
		}
	}
	return fmt.Errorf("scene(%s) 404 not found", id)
}

func (sm *SceneManager) setScenes(scenes []*Scene)  {
	sm.scenes = scenes
}

func (sm *SceneManager) findSceneById(id string) *Scene {
	for _, s := range sm.scenes {
		if s.Id == id {
			return s
		}
	}
	return nil
}

type ScenePost struct {
	Type 	string				`json:"type"`
	Id 		string				`json:"id"`
	Data 	json.RawMessage		`json:"data"`
}

const (
	scenePostExecute 	= 	"execute"
	scenePostUpsert 	= 	"upsert" 	// 更新插入
	scenePostDelete 	= 	"delete"
)

func (sm *SceneManager) Handle(h *Home, pkg *members.MessagePkg) error {
	msg := pkg.Msg
	if msg.Method == members.MsgMethodGet {
		buf, _ := json.Marshal(sm.scenes)
		ack := &members.MessagePkg{
			Type: pkg.Type,
			Ctx: pkg.Ctx,
			Msg: &members.Message{
				Path: msg.Path,
				Method: msg.Method,
				State: "ok",
				Home: h.Id,
				Data: buf,
			},
		}
		h.replyMemberResult(ack)

	// 更新场景或者执行场景
	} else if msg.Method == members.MsgMethodPost {
		var post ScenePost
		if err := json.Unmarshal(msg.Data, &post); err != nil {
			log.Debug("%s", err)
			return err
		}
		if post.Type == scenePostExecute {
			if scene := sm.findSceneById(post.Id); scene != nil {
				scene.execute(h)
			}
		}
	}
	return nil
}

